//
//  NetWorkTaskHandle.m
//  UI_DOUBAN
//
//  Created by ChuXiang on 15/11/20.
//  Copyright © 2015年 ChuXiang. All rights reserved.
//

#import "NetWorkTaskHandle.h"

@implementation NetWorkTaskHandle

+ (void)sendTask:(NSString *)url withBody:(NSData *)body withResult:(void (^)(id result))block {
    NSURLSession *session = [NSURLSession sharedSession];
    NSMutableURLRequest *requst = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
    [requst setHTTPMethod:@"POST"];
    [requst setHTTPBody:body];
    NSURLSessionDataTask *task = [session dataTaskWithRequest:requst completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (!error) {
            id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            block(result);
        }
    }];
    [task resume];
}

+ (void) sendTask:(NSString *)url withResult:(void (^)(id result))block {
    NSURL *url1 = [NSURL URLWithString:url];
    //    获取session对象
    //        NSURLSession *session = [NSURLSession sharedSession];
//        NSURLSessionTask *task = [session dataTaskWithURL:requst completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
//    
//            id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
////            block(result);
//            NSLog(@"%@", result);
//        }];
//    //    启动任务
//        NSLog(@"同步/异步");
//        [task resume];
    NSURLRequest *requst = [NSURLRequest requestWithURL:url1];
    [NSURLConnection sendAsynchronousRequest:requst queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        
        if (!connectionError) {
            //            data就是网络请求返回的数据
            //            数据处理
            id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            block(result);
        }
    }];

}
@end
